﻿
using Microsoft.AspNetCore.Http;
using NetCore.Cache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NetCore
{
    public class AppHttpContext
    {
        private static IHttpContextAccessor m_httpContextAccessor;
        public static void Configure(IHttpContextAccessor httpContextAccessor)
        {
            m_httpContextAccessor = httpContextAccessor;

        }
        public static HttpContext Current
        {
            get
            {
                return m_httpContextAccessor.HttpContext;
            }
        }
        public static T GetSerivce<T>()
        {
            return (T)Current.RequestServices.GetService(typeof(T));
        }
        public static bool IsPost
        {
            get
            {
                if (m_httpContextAccessor.HttpContext.Request.Method.ToLower().Equals("post"))
                {
                    return true;
                }
                return false;
            }
        }
        public static bool IsAjax
        {
            get
            {
                string sheader = Current.Request.Headers["X-Requested-With"];
                return (sheader != null && sheader == "XMLHttpRequest") ? true : false;

            }
        }

        private static ICacheService _cacheService;
        private static object _locker = new object();
        public static ICacheService CacheService
        {
            get
            {
                if (_cacheService == null)
                {
                    lock (_locker)
                    {
                        if (ApplicationEnvironments.IsWeb)
                        {
                            _cacheService = AppHttpContext.GetSerivce<ICacheService>();
                        }
                        if (_cacheService == null)
                        {
                            if (!ApplicationEnvironments.Site.IsUseRedis)
                            {
                                _cacheService = new MemoryService();
                            }
                            else
                            {
                                _cacheService = new RedisService();
                            }
                        }
                    }
                }
                return _cacheService;
            }
        }

        private static IDbRepository _dbService;
        public static IDbRepository DbService
        {
            get
            {
                if (_dbService == null)
                {
                    _dbService = AppHttpContext.GetSerivce<IDbRepository>();
                }
                return _dbService;
            }
        }

        /// <summary>
        /// 用户认证Key
        /// </summary>
        public const string TokenKeyName = "access_token";
    }
   
}